package com.sunop.userservice.controller;


import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.sunop.panticommon.annotation.RateLimit;
import com.sunop.panticommon.entity.Result;
import com.sunop.userservice.model.*;
import com.sunop.userservice.service.RoleService;
import com.sunop.userservice.service.UserService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {

    private final UserService userService;
    private final RoleService roleService;

    @GetMapping("/getUserId")
    @SaCheckRole("teacher")
    public Result getUserId() {
            return Result.success(StpUtil.getLoginIdAsInt());
    }


    @PostMapping("/login")
    @RateLimit(userQps = 5, ipMaxRequests = 10, ipBanMinutes = 10)
    public Result login(@RequestParam String username, String password) {
        if(username == null || password == null)return Result.error("请输入账号和密码");
        Integer userid = 0;
        try {
            userid = userService.selectByNameAndPassword(username, password);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("登录失败，请稍后重试");
        }

        // 检查 userid 是否为 null
        if (userid == null) {
            return Result.error("账号或密码错误");
        }
        StpUtil.login(userid, new SaLoginModel().setTimeout(60 * 60 * 24 ));// 设置登录有效期1天
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

        return Result.success(tokenInfo, "登录成功");
    }

    @PostMapping("/logout")
    public Result logout() {
        StpUtil.logout();
        return Result.success(null,"已成功登出");
    }

    @PostMapping("/sendCode")
    public Result sendVerificationCode(@RequestParam String email) {
        return userService.sendVerificationCode(email);
    }

    @PostMapping("/register")
    @Validated
    public Result register(@Valid @RequestBody UserRegisterDto userRegisterDto) {
        return userService.register(userRegisterDto);
    }

    @GetMapping("/getUserInfo")
    public Result getUserInfo() {
        Integer userid = StpUtil.getLoginIdAsInt();
        User user = userService.getById(userid);
        UserRole userRole = roleService.getById(userid);
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(user, userInfo);
        BeanUtils.copyProperties(userRole, userInfo);
        return Result.success(userInfo);
    }
    @PatchMapping("/updateUserInfo")
    public Result updateUserInfo(@RequestBody UserUpdateInfo userInfo) {
        return userService.updateInfo(userInfo);
    }

    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file)  {
        return userService.uploadFile(file);
    }

    @GetMapping("/download")
    public void downloadFile(HttpServletResponse response) {
        try {
            String path = userService.getFilePath();
            InputStream inputStream = userService.downloadFile(path);
            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + URLEncoder.encode(
                            path.substring(path.lastIndexOf("/") + 1),
                            StandardCharsets.UTF_8
                    )
            );

            // 将文件流写入响应
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e) {
            response.reset(); // 清除已写入的响应内容
            response.setContentType("application/json;charset=utf-8");
            try {
                response.getWriter().write(Result.error("文件下载失败: " + e.getMessage()).toString());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    //后台管理用，装样子的，能用，但已经自动删了
//    @DeleteMapping("/delete")
//    public void deleteFile(@RequestParam("path") String path) {
//        ossService.deleteFile(path);
//    }
    @GetMapping("/feign/getUserBaseDTO")
    public UserBaseDTO getUserBaseDTO(@RequestParam Integer userId) {
        UserBaseDTO userBaseDTO = userService.getUserBaseDTO(userId);
        return userBaseDTO;
    }

    @GetMapping("/fegin/getclassId")
    public int getclassId(int userId) {
        return userService.getclassId(userId);
    }
    @GetMapping("/fegin/getUserOverProblemIds")
    public List<Integer> getUserOverProblemIds(int userId) {
        return userService.getUserOverProblemIds(userId);
    }
}
